{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "54aee65f",
   "metadata": {},
   "source": [
    "# 百度AI开放平台\n",
    "通用物体和场景识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76deaa0e",
   "metadata": {},
   "source": [
    "* 接口描述\n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "* 请求示例\n",
    "> HTTP 方法：POST\n",
    "* 请求URL\n",
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96da50be",
   "metadata": {},
   "source": [
    "## 鉴权认证机制(access_token)\n",
    "> 获取Access Token                                   \n",
    "> 获取access_token示例代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "da3f4837",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.0a4847c4881648916c3aa640a0a39393.315360000.1965533415.282335-25863406', 'expires_in': 2592000, 'session_key': '9mzdAvuLwJPxrzFk9RaLYEW/UhPlFymEQei+EpeHWfMJMi0Sy8nfAfMfHmtGssiNTSJRQTXmt/mXMFcdbiA3ak0HQu/0GA==', 'access_token': '24.9907c98632c5421cb53b5382513e1ed2.2592000.1652765415.282335-25863406', 'scope': 'brain_ocr_accurate_basic public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '457aa0f857c8df08336cdbb3333f1753'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'uf0BqIVkKd6qof7GuSc9dvjk',\n",
    "    'client_secret':'w6QrzMlRjytBS8oO3zdPa9vWqEAj444y'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c2fefedd",
   "metadata": {},
   "outputs": [],
   "source": [
    "lvow_AI = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bfcc7476",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "54197266",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f8dec94c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '海洋', 'score': 0.776897, 'root': '自然风景-海洋', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B5%B7%E6%B4%8B/523', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/77094b36acaf2eddba6728be871001e9380193d6', 'description': '海洋(sea)，地理名词，是地球上最广阔的水体的总称。地球表面被各大陆地分隔为彼此相通的广大水域称为海洋，海洋的中心部分称作洋，边缘部分称作海，彼此沟通组成统一的水体。地球上海洋总面积约为3.6亿平方千米，约占地球表面积的71%，平均水深约3795米。海洋中含有十三亿五千多万立方千米的水，约占地球上总水量的97%，而可用于人类饮用只占2%。地球四个主要的大洋为太平洋、大西洋、印度洋、北冰洋，大部分以陆地和海底地形线为界。当今人类已探索的海底只有5%，还有95%大海的海底是未知的。'}}, {'keyword': '湖泊', 'score': 0.61234, 'root': '自然风景-湖泊', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B9%96%E6%B3%8A/242936', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8435e5dde71190ef635cd56ccd1b9d16fcfa60d9', 'description': '湖盆及其承纳的水体。湖盆是地表相对封闭可蓄水的天然洼池。湖泊按成因可分为构造湖、火山口湖、冰川湖、堰塞湖、喀斯特湖、河成湖、风成湖、海成湖和人工湖(水库)等。按泄水情况可分为外流湖(吞吐湖)和内陆湖；按湖水含盐度可分为淡水湖(含盐度小于1g/L)、咸水湖(含盐度为1-35g/L)和盐湖(含盐度大于35g/L)。湖水的来源是降水、地面径流、地下水，有的则来自冰雪融水。湖水的消耗主要是蒸发、渗漏、排泄和开发利用。'}}, {'keyword': '港口码头', 'score': 0.409452, 'root': '建筑-现代建筑', 'baike_info': {}}, {'keyword': '江河', 'score': 0.223182, 'root': '自然风景-江河', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%B1%9F%E6%B2%B3/9571871', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/4034970a304e251f9b897931a686c9177e3e53f8', 'description': '江河，男，原名于友泽，1949年生，北京人，1968年高中毕业。1980年5月在《上海文学》发表处女作《星星变奏曲》，著有诗集《从这里开始》《太阳和它的反光》等，是新时期朦胧诗派的代表诗人之一。他的诗作中灌注了相当厚重的历史感，以《纪念碑》等政治抒情诗和古代神话组诗《太阳和它的反光》赢得社会瞩目。与顾城、北岛、舒婷,杨炼一起并称为“五大朦胧诗人”。'}}, {'keyword': '天空', 'score': 0.056238, 'root': '自然风景-天空', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A4%A9%E7%A9%BA/5534', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/241f95cad1c8a7868fa019076909c93d70cf5034', 'description': '天空，汉语词汇，拼音tiān kōng，谓天际空阔；日月星辰罗列的广大空间。是地球重要的组成部分，在古代中国有天圆地方的说法。人可以在天空观测气象或天文现象，从而得知天气变化、时间的流逝或自己的方位。日出日落可知一日中的时间，晚上月亮的盈亏可以知道一个月的时间。北斗星可以指示北方。云的厚度和形状可以知道会否下雨。 在天空可以欣赏到许多美丽的现象，如彩虹、极光和流星雨等。雀鸟会在天空飞翔。 由于石油等化石性燃料使用的增加而产生的悬浮质，特别是那些会在燃烧后释放二氧化硫的煤等燃料的影响，自1973年以来，除了欧洲，天空的能见度正在逐步降低。'}}], 'log_id': 1515563368082951860}\n"
     ]
    }
   ],
   "source": [
    "# 例子\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('xihu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':lvow_AI,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7f8442dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'name': '鱼香肉丝', 'calorie': '154', 'probability': '0.954351', 'baike_info': {}, 'has_calorie': True}, {'name': '酱肉丝', 'calorie': '240', 'probability': '0.0304891', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%85%B1%E8%82%89%E4%B8%9D/2689787', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b90e7bec54e736d1fb1014b39b504fc2d562690e', 'description': '酱肉丝是一道传统的家常菜，主要制作食材是猪里脊肉，配料是豆腐皮等，调料是甜面酱、白糖、料酒等，通过大火烧制而成。'}, 'has_calorie': True}, {'name': '肉丝饭', 'calorie': '268', 'probability': '0.0076399', 'baike_info': {}, 'has_calorie': True}, {'name': '肉丝', 'calorie': '174', 'probability': '0.00196575', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%82%89%E4%B8%9D/5216182', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/562c11dfa9ec8a13ab7a3a71fd03918fa0ecc03b', 'description': '肉丝即为切成丝状的肉，主要是指猪肉肉丝。肉丝菜主要有青椒肉丝、春笋肉丝、肉丝芝麻、龙爪肉丝、茭白肉丝、酱爆肉丝、钱江肉丝等。'}, 'has_calorie': True}, {'name': '青椒肉丝', 'calorie': '99', 'probability': '0.00066992', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%9D%92%E6%A4%92%E8%82%89%E4%B8%9D/321196', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/11385343fbf2b211f6c04120c48065380dd78ef6', 'description': '青椒肉丝，是以青椒为主要食材的家常菜，属于川菜菜系。口味香辣，菜品色香味俱全，操作简单，营养价值丰富。青椒肉丝属于辛辣类菜品，眼疾患者、食管炎、胃肠炎、胃溃疡、痔疮患者应少吃或忌食。同时有火热病症或阴虚火旺，高血压，肺结核病的人慎食。'}, 'has_calorie': True}], 'log_id': 1515563378865802207}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('yuxiangrousi.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "\n",
    "access_token = lvow_AI\n",
    "payload={\n",
    "    'access_token':lvow_AI,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f3c5422b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'score': 0.7598952, 'name': '玉蝉花', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%8E%89%E8%9D%89%E8%8A%B1/2221688', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/3bf33a87e950352a103995775743fbf2b2118b71', 'description': '玉蝉花(Iris ensata Thunb.)：多年生草本，植株基部围有叶鞘残留的纤维。根状茎粗壮，斜伸，外包有棕褐色叶鞘残留的纤维；须根绳索状，灰白色，有皱缩的横纹。叶条形，两面中脉明显。花茎圆柱形，实心，有1-3枚茎生叶；苞片3枚，近革质，披针形，内包含有2朵花；花深紫色，直径9-10厘米；外花被裂片倒卵形，内花被裂片小，直立，狭披针形或宽条形。蒴果长椭圆形，顶端有短喙，6条肋明显，成熟时自顶端向下开裂至1/3处；种子棕褐色，扁平，半圆形，边缘呈翅状。花期6-7月，果期8-9月。生于沼泽地或河岸的水湿地。产中国黑龙江、吉林、辽宁、山东、浙江，也产于朝鲜、日本及苏联。此花有栽培，具有较高的园艺价值。(概述图片参考资料来源：)'}}, {'score': 0.33954698, 'name': '鸢尾', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%B8%A2%E5%B0%BE/784374', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/5fdf8db1cb1349542259b6915c4e9258d0094afb', 'description': '鸢尾(学名：Iris tectorum Maxim.)又名：蓝蝴蝶、紫蝴蝶、扁竹花等，属百合目、鸢尾科、鸢尾属多年生草本，根状茎粗壮，直径约1cm，斜伸；叶长15~50cm，宽1.5~3.5cm，花蓝紫色，直径约10cm；蒴果长椭圆形或倒卵形，长4.5~6cm，直径2~2.5cm。原产于中国中部以及日本，主要分布在中国中南部。可供观赏，花香气淡雅，可以调制香水，其根状茎可作中药，全年可采，具有消炎作用。'}}, {'score': 0.06559799, 'name': '矮鸢尾', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%9F%AE%E9%B8%A2%E5%B0%BE/551629', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/5d6034a85edf8db162c8a12e0423dd54574e7492', 'description': '矮鸢尾(学名：Iris kobayashii)是属于鸢尾科鸢尾属的一种植物。是中国的特有植物。矮生草本，高约10厘米。茎极短，为叶片所包裹。叶剑形，长7~12厘米，宽6~10米。花葶从叶丛中伸出，着花1朵，花色繁多，有黄白、紫等色。花期4~5月。分布于中国大陆的辽宁等地，见于干燥的丘陵地，尚未由人工引种栽培。'}}, {'score': 0.060905267, 'name': '德国鸢尾', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%BE%B7%E5%9B%BD%E9%B8%A2%E5%B0%BE/1193911', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/a044ad345982b2b733f684a735adcbef76099b6c', 'description': '德国鸢尾(学名：Iris germanica L.)是鸢尾科鸢尾属植物，多年生草本。根状茎粗壮而肥厚，常分枝，扁圆形，斜伸，具环纹，黄褐色；须根肉质，黄白色。叶直立或略弯曲，淡绿色、灰绿色或深绿色，常具白粉，剑形。花茎光滑，黄绿色。花大，鲜艳，直径可达12厘米；花色因栽培品种而异，多为淡紫色、蓝紫色、深紫色或白色，有香味。蒴果三棱状圆柱形，顶端钝，无喙，成熟时自顶端向下开裂为三瓣；种子梨形，黄棕色，表面有皱纹，顶端生有黄白色的附属物。花期4-5月，果期6-8月。原产于欧洲中部和南部。中国各地庭园常见栽培。对土壤要求不严，抗旱、抗寒能力强。喜温暖、稍湿润和阳光充足环境。耐寒，耐干燥和半阴，怕积水。宜疏松、肥沃和排水良好的含石灰质土壤。德国鸢尾耐寒性强，生长健壮，有深紫、纯白、桃红、淡紫等颜色，是极好的观花地被植物，在园林绿化中常用于花坛、花境布置。同时，可盆栽观赏，也是重要的切花材料。(概述图参考来源：)'}}, {'score': 0.053501323, 'name': '花菖蒲', 'baike_info': {}}], 'log_id': 1515563385284056282}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('yuanweihua.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':lvow_AI,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39a51dc3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
